#include "changeuseravatartask.h"
#include "libs/base/service/uploader.h"
#include "libs/base/utils/copyfile.h"
#include "libs/core/user/localuser.h"
#include "services/yingceservice.h"
#include "usersettings.h"
#include "yingce.h"

ChangeUserAvatarTask::ChangeUserAvatarTask(const QString& path, QObject* parent)
    : yc::Task { 0, true, 0, parent }, path_(path)
{
}

void ChangeUserAvatarTask::startImpl()
{
    const QDir res_dir = UserSettings::instance().resDir();
    const QString new_path = yc::CopyFileWorker::copyTo(path_, res_dir.absolutePath(), QString());
    if (new_path.isEmpty()) {
        Q_EMIT failed(yc::LOGIC_ERROR, tr("Failed to calculate file md5."));
        return;
    }

    QFileInfo fi(new_path);
    const QString name = fi.fileName();
    QList<yc::UploadResource> uploads;
    uploads.push_back(yc::UploadResource { name, fi.size(), name });

    const QString service_url = UserSettings::instance().serviceUrls().cloud_upload;
    yc::Uploader* t = new yc::Uploader(YingCeService::instance(), service_url,
                                       res_dir.absolutePath(), uploads, this);
    t->setHeaders(YingCeService::instance()->headers());
    connect(t, &yc::Uploader::failed, this, [this](int error, const QString& message) {
        Q_UNUSED(error)
        Q_EMIT failed(yc::SERVICE_ERROR,
                      tr("Failed to upload the avatar, the error is \"%1\".").arg(message));
    });
    connect(t, &yc::Uploader::finished, this, [this, name] {
        YingCeService::instance()->changeUserAvatar(
                name,
                yc::ResponseHandler(
                        this,
                        [this, name](const yc::Request& request, const yc::Response& response) {
                            if (response.status() == yc::OK_CODE) {
                                YingCe::instance()->localUser()->setAvatar(name);
                                Q_EMIT this->finished();
                            } else {
                                Q_EMIT this->failed(
                                        response.status(),
                                        tr("Failed to upload the avatar, the error is \"%1\".")
                                                .arg(response.msg()));
                            }
                        }));
    });
    t->start();
}
